package com.zhong.filter;

import jodd.JoddDefault;
import jodd.io.StreamUtil;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author zbg on 2019-02-14 14:54:31
 */
public class WrappedHttpRequest extends HttpServletRequestWrapper {
    private String uri;
    private final byte[] body;

    public String getRequestURI() {
        return this.uri;
    }

    public void setRequestURI(String u) {
        this.uri = u;
    }

    public String getServletPath() {
        return this.uri;
    }

    public StringBuffer getRequestURL() {
        return new StringBuffer(this.uri);
    }

    private WrappedHttpRequest(HttpServletRequest request) throws IOException {
        super(request);
        this.body = StreamUtil.readBytes(request.getReader(), JoddDefault.encoding);
        this.uri = request.getRequestURI();
    }

    public static WrappedHttpRequest wrap(HttpServletRequest request) throws IOException {
        return request instanceof WrappedHttpRequest ? (WrappedHttpRequest)request : new WrappedHttpRequest(request);
    }

    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream bais = new ByteArrayInputStream(this.body);
        return new ServletInputStream() {
            public boolean isFinished() {
                return false;
            }

            public boolean isReady() {
                return false;
            }

            public void setReadListener(ReadListener listener) {
            }

            public int read() throws IOException {
                return bais.read();
            }
        };
    }
}
